package service

import (
	"encoding/json"
	"fmt"
	"github.com/aliyun/alibaba-cloud-sdk-go/services/dysmsapi"
	"learngin/config"
	"learngin/model"
	"math/rand"
	"time"
)

func SendCode(mobile string, status int) (bool, string) {
	code := fmt.Sprintf("%06v", rand.New(rand.NewSource(time.Now().UnixNano())).Int31n(1000000))
	sms := config.Cfg.Sms
	client, _ := dysmsapi.NewClientWithAccessKey(sms.RegionId, sms.AppKey, sms.AppSecret)
	request := dysmsapi.CreateSendSmsRequest()
	par, _ := json.Marshal(map[string]interface{}{
		"code": code,
	})
	request.Scheme = "https"
	request.SignName = sms.SignName
	request.PhoneNumbers = mobile
	request.TemplateCode = sms.TemplateCode
	request.TemplateParam = string(par)
	response, err := client.SendSms(request)
	if err != nil {
		fmt.Print(err.Error())
		return false, response.Message
	}
	if response.Code != "OK" {
		return false, response.Message
	}
	result := model.InsertSmsCode(mobile, status, response.BizId, code)
	if !result {
		return false, "短信发送失败"
	}
	return true, "短信发送成功"
}
